import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import memcache


class Calculate(webapp.RequestHandler):
  def get(self):
    n = int(self.request.get('n', default_value='0'))
    self.count = 0
    product = self.factorial(n)
    logging.info("Calculation count = %d", self.count)
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write(product)

  def mutiple(self, a, b):
    product = a * b;
    while product % 10 == 0:
      product /= 10
    product %= 10000000000
    self.count += 1
    return product

  def factorial(self, n):
    product = 1
    for i in xrange(1, n + 1):
      product = self.mutiple(product, i)
    return product
  

class ResumableCalculate(Calculate):
  step = 10000

  def partial_factorial(self, start):
    key = str(start) + ',' + str(start + self.step - 1)
    product = memcache.get(key)
    if product is None:
      product = 1
      for i in xrange(start, start + self.step):
        product = self.mutiple(product, i)
      memcache.set(key, product)
    return product

  def factorial(self, n):
    product = 1
    start = 1
    while start + self.step - 1 <= n:
      product = self.mutiple(product, self.partial_factorial(start))
      start += self.step
    for i in xrange(start, n + 1):
      product = self.mutiple(product, i)
    return product


class Clear(webapp.RequestHandler):
  def get(self):
    if memcache.flush_all():
      self.response.out.write('Success!')
    else:
      self.response.out.write('Fail!')


application = webapp.WSGIApplication(
    [('/factorial', Calculate), 
     ('/resumable-factorial', ResumableCalculate),
     ('/clear', Clear)], 
    debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
